package utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.StringTokenizer;

public class CalculadoraFama {

	public CalculadoraFama() {
	}

	public Long calcularFama(String accion) {
		try {

			Long res = 0L;

			if (accion.contains(" ")) {

				StringTokenizer st = new StringTokenizer(accion, " ");
				accion = "";
				while (st.hasMoreTokens())
					accion += st.nextToken();

			}

			URL yahoo = new URL("http://es.search.yahoo.com/search?vc=&p="
					+ accion + "&toggle=1&cop=mss&ei=UTF-8&fr=yfp-t-705");
			URLConnection yc = yahoo.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc
					.getInputStream()));
			String inputLine;
			String s1 = "<strong id=\"resultCount\">";
			String s2 = "</strong>";
			String cadenTotal = "";

			while ((inputLine = in.readLine()) != null) {
				cadenTotal += inputLine;
			}

			in.close();

			Integer indice = cadenTotal.indexOf(s1);
			String cadenaMitad = cadenTotal.substring(indice + 25);
			String cadenaFinal = cadenaMitad.substring(0, cadenaMitad
					.indexOf(s2));

			String fin = "";

			StringTokenizer st = new StringTokenizer(cadenaFinal, ".");
			while (st.hasMoreTokens())
				fin += st.nextToken();

			res = new Long(fin.toString());
			res = res / 1000;
			return res;

		}// try
		catch (Exception ex) {
			ex.printStackTrace();
			return 0L;
		}

	}

	public static void main(String[] args) {
		System.out.println((new CalculadoraFama()).calcularFama("Apple"));

	}
}